﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Configuration.Install;
using System.Text.RegularExpressions;
using System.IO;
using System.Data;
using System.Data.SqlClient;
using System.Windows.Forms;
using System.Reflection;

namespace InstallHealthCheckDatabase
{
    [RunInstaller(true)]
    public partial class SQLHealthCheckDBInstaller : System.Configuration.Install.Installer
    {
        public SQLHealthCheckDBInstaller()
        {
           
            InitializeComponent();
           
        }



        public override void Install(IDictionary stateSaver)
        {
            base.Install(stateSaver);
           
            RunDBSetup(Context.Parameters["dbname"].ToString());
        }

       
       

        public bool RunDBSetup(string databaseserver)
        {

            try
            {
                string FileName = Application.StartupPath + @"\SQLServerHealthCheck.Database.sql";

                ReplaceInFile(FileName, @":setvar DefaultDataPath """"", string.Empty);
                ReplaceInFile(FileName, @":setvar DefaultLogPath """"", string.Empty);
                databaseserver = databaseserver.Replace(@"\\", @"\");
                string CommandLineString = "-S" + databaseserver + " -vDefaultDataPath=" + @"""" + GetDataFilePath(databaseserver) + @""" -i""" + FileName + @"""";
                CommandLineString = CommandLineString.Replace(@"\\", @"\");
                           
                System.Diagnostics.ProcessStartInfo myInfo = new System.Diagnostics.ProcessStartInfo("SQLCMD", CommandLineString);
                myInfo.UseShellExecute = false;
                myInfo.CreateNoWindow = true;
                myInfo.RedirectStandardOutput = true;

                System.Diagnostics.Process p = new System.Diagnostics.Process();
                p.StartInfo = myInfo;
                p.Start();
                //wait 5 seconds for this to finish
                System.Threading.Thread.Sleep(10000);
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message.ToString() + "    " + ex.StackTrace.ToString());
            }
            return true;

        }


        private string GetDataFilePath(string databaseserver)
        {
            string strDataFilepath = "";
            SqlConnection conn = new SqlConnection(@"Server=" + databaseserver + ";Database=master;Integrated Security=True");
            conn.Open();
            SqlCommand ocmd = new SqlCommand("select SUBSTRING([filename],0, CHARINDEX([name],[filename],0)) as DataFilePath from sys.sysaltfiles where dbid=1 and fileid=1", conn);
            SqlDataReader rd = ocmd.ExecuteReader();

            if (rd.Read())
            {

                strDataFilepath = rd["DataFilePath"].ToString();
            }

            rd.Close();
            return strDataFilepath;

        }

        private string GetLogFilePath(string databaseserver)
        {
            string strLogFilepath = "";
            SqlConnection conn = new SqlConnection(@"Server=" + databaseserver + ";Database=master;IntegratedSecurity=true");
            conn.Open();
            SqlCommand ocmd = new SqlCommand("select SUBSTRING([filename],0, CHARINDEX([name],[filename],0))  as LogFilePath from sys.sysaltfiles where dbid=1 and fileid=2", conn);
            SqlDataReader rd = ocmd.ExecuteReader();

            if (rd.Read())
            {

                strLogFilepath = rd["LogFilePath"].ToString();
            }

            rd.Close();
            return strLogFilepath;

        }


        public void ReplaceInFile(string filePath, string searchText, string replaceText)
        {
            StreamReader reader = new StreamReader(filePath);
            string content = reader.ReadToEnd();
            reader.Close();

            content = Regex.Replace(content, searchText, replaceText);

            StreamWriter writer = new StreamWriter(filePath);
            writer.Write(content);
            writer.Close();
        }


     
    



    }
}
